import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/port.dart';
import 'package:mall/core/models/team_and_port.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/group/components/port_open_sheet.dart';
import 'package:mall/components/clock_countdown.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../order/order_confirm_screen.dart';

class GroupPortScreenArgs {
  GroupPortScreenArgs(
    this.modelInAreaId,
    this.productImage,
  );

  final int modelInAreaId;
  final String productImage;
}

/// 拼购窗口页面
class GroupPortScreen extends StatefulWidget {
  static const routeName = "/GroupPortScreen";
  final GroupPortScreenArgs args;

  const GroupPortScreen({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  _GroupPortScreenState createState() => _GroupPortScreenState();
}

class _GroupPortScreenState extends State<GroupPortScreen> {
  String _error;
  TeamAndPort _teamAndPort;
  RefreshController _refreshController;
  int _pageIndex;
  final List<Port> _list = [];
  final List<int> _selectedPortIds = []; // 选中的窗口

  @override
  void initState() {
    super.initState();
    _onRefresh();
    _refreshController = RefreshController();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("我要拼"),
      ),
      body: _error == null && _teamAndPort == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _teamAndPort == null
              ? Center(
                  child: Text('$_error'),
                )
              : _buildBody(),
    );
  }

  Widget _buildBody() {
    return SafeArea(
      child: Column(
        children: [
          Expanded(
            child: SmartRefresher(
              controller: _refreshController,
              enablePullUp: _teamAndPort.portVos.length == 10,
              onRefresh: _onRefresh,
              onLoading: _onLoading,
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    buildHeader(),
                    Wrap(
                      spacing: 8.w,
                      runSpacing: 8.w,
                      children: List.generate(_list.length, (index) => _buildItem(index)),
                    ),
                    SizedBox(height: 8.w),
                  ],
                ),
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 8.w),
            color: Colors.white,
            height: 50.w,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                SizedBox(
                  child: OutlineButton(
                    onPressed: _portOpen,
                    borderSide: BorderSide(color: Theme.of(context).primaryColor),
                    child: Text("开通更多子账户"),
                  ),
                ),
                SizedBox(width: 8.w),
                SizedBox(
                  child: RaisedButton(
                    onPressed: _selectedPortIds.isEmpty ? null : _confirm,
                    elevation: 0,
                    child: Text("立即拼购"),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget buildHeader() {
    return Padding(
      padding: EdgeInsets.all(8.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("${_teamAndPort.totalPrice}拼购"),
                  SizedBox(height: 4.w),
                  Text("第 ${_teamAndPort.teamCode} 期"),
                  SizedBox(height: 4.w),
                  ClockCountdown(
                    endTime: _teamAndPort.startTime.add(Duration(seconds: _teamAndPort.maxTimeLen)),
                    fontSize: 16.sp,
                    onEnd: _onEnd,
                  ),
                ],
              ),
              ClipRRect(
                borderRadius: BorderRadius.circular(4.w),
                child: Container(
                  color: Colors.white,
                  child: ImageNetwork(
                    url: "${widget.args.productImage}",
                    width: 80.w,
                    height: 80.w,
                  ),
                ),
              )
            ],
          ),
          // 白色横线
          Divider(height: 32.w, thickness: 2.w, color: Colors.white),
          // 账户信息、全选按钮
          Text.rich(
            TextSpan(
              text: "你的账户${_teamAndPort.joinFeeAccountTypeName}余额：",
              style: TextStyle(color: Colors.black, fontSize: 12.sp),
              children: [
                TextSpan(
                  text: "${_teamAndPort.joinFeeAccountBalance}",
                  style: TextStyle(color: Theme.of(context).primaryColor),
                )
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text.rich(
                TextSpan(
                  text: "共有${_teamAndPort.curPortCount}个账户可参与拼购 ",
                  style: TextStyle(color: Colors.black, fontSize: 12.sp),
                  children: [
                    TextSpan(
                      text: "(点击卡片选择)",
                      style: TextStyle(color: Theme.of(context).primaryColor),
                    )
                  ],
                ),
              ),
              SizedBox(
                height: 24.w,
                child: RaisedButton(
                  onPressed: _selectAll,
                  elevation: 0,
                  color: Colors.orange[300],
                  child: Text(
                    _canJoinList().length == _selectedPortIds.length ? '全部取消' : "全部选择",
                    style: TextStyle(color: Colors.white, fontSize: 12.sp),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _onEnd() async {
    // 延迟3秒
    await Future.delayed(Duration(seconds: 3));
    if (!mounted) {
      return;
    }
    // 刷新
    _onRefresh();
  }

  Widget _buildItem(int index) {
    final port = _list[index];
    return GestureDetector(
      onTap: () => _onTapItem(port),
      child: Container(
        padding: EdgeInsets.all(8.w),
        width: (375.0 - 8 * 2).w,
        decoration: BoxDecoration(
          color: _selectedPortIds.contains(port.id) ? Colors.orange[100] : Colors.white,
          borderRadius: BorderRadius.circular(4.w),
        ),
        child: Column(
          children: [
            Row(
              children: [
                Image.asset(
                  "assets/icons/account.png",
                  width: 18.w,
                  color: port.canJoin() ? Theme.of(context).primaryColor : Colors.grey,
                ),
                SizedBox(width: 8.w),
                Text(
                  "${port.portName}",
                  style: TextStyle(color: Colors.black),
                ),
                Spacer(),
                if (_selectedPortIds.contains(port.id)) Icon(Icons.done),
              ],
            ),
            SizedBox(height: 8.w),
            Row(
              children: [
                SizedBox(width: 8.w),
                SizedBox(
                  height: 24.w,
                  child: FlatButton(
                    onPressed: port.hitTotal >= port.joinTotal + 1 ? () => _exchange(port) : null,
                    child: Text('兑换点卷'),
                  ),
                ),
                Spacer(),
                Text("余${port.joinToday} / 兑${port.hitTotal} / 需${port.joinTotal}"),
              ],
            )
          ],
        ),
      ),
    );
  }

  /// 第一页
  void _onRefresh() async {
    _pageIndex = 0;
    final api = context.read<Api>();
    try {
      final teamAndPort = await api.groupPurchaseQuery(widget.args.modelInAreaId, _pageIndex);
      if (!mounted) {
        return;
      }
      if (teamAndPort.statusText != null && teamAndPort.statusText.isNotEmpty) {
        throw teamAndPort.statusText ?? '还未开始';
      }
      _refreshController.refreshCompleted();
      setState(() {
        _teamAndPort = teamAndPort;
        _list.clear();
        _list.addAll(teamAndPort.portVos);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.refreshFailed();
      setState(() {
        _error = e.message;
      });
    } catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.refreshFailed();
      setState(() {
        _error = '$e';
      });
    }
  }

  /// 更多页
  void _onLoading() async {
    _pageIndex++;
    final api = context.read<Api>();
    try {
      final teamAndPort = await api.groupPurchaseQuery(widget.args.modelInAreaId, _pageIndex);
      if (!mounted) {
        return;
      }
      _refreshController.loadComplete();
      setState(() {
        _teamAndPort = teamAndPort;
        _list.addAll(teamAndPort.portVos);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.loadFailed();
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 全部选择
  void _selectAll() {
    setState(() {
      var canJoinList = _canJoinList();
      if (canJoinList.length == _selectedPortIds.length) {
        _selectedPortIds.clear();
      } else {
        _selectedPortIds.clear();
        _selectedPortIds.addAll(canJoinList.map((e) => e.id));
      }
    });
  }

  /// 能参加的列表
  List<Port> _canJoinList() {
    // 没有参加的，并且今日可拼购次数没有用完的。
    return _list.where((element) => element.canJoin()).toList();
  }

  /// 点击窗口
  void _onTapItem(Port port) {
    setState(() {
      if (_selectedPortIds.contains(port.id)) {
        _selectedPortIds.remove(port.id);
      } else if (port.canJoin()) {
        _selectedPortIds.add(port.id);
      }
    });
  }

  /// 兑换
  void _exchange(Port port) async {
    final result = await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Text("确认使用兑换卷兑换分红点数？"),
          actions: [
            FlatButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text("取消"),
            ),
            FlatButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: Text("确定"),
            ),
          ],
        );
      },
    );
    if (result == null) {
      return;
    }
    // 确定
    final api = context.read<Api>();
    EasyLoading.show();
    try {
      await api.groupPurchaseClearHit(widget.args.modelInAreaId, port.id);
      EasyLoading.showToast("兑换成功");
      // 刷新
      _onRefresh();
    } on DioError catch (e) {
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 开通窗口
  void _portOpen() async {
    final result = await showModalBottomSheet(
      context: context,
      builder: (_) => PortOpenSheet(
        miaId: widget.args.modelInAreaId,
        teamAndPort: _teamAndPort,
      ),
      isScrollControlled: true,
    );
    if (result != null) {
      _onRefresh();
    }
  }

  /// 立即拼购
  /// 1、添加到购物车
  void _confirm() async {
    final api = context.read<Api>();
    EasyLoading.show();
    try {
      final cartAdd = await api.cartAdd(widget.args.modelInAreaId, 1, null, replace: true);
      if (!mounted) {
        return;
      }
      EasyLoading.dismiss();
      // 转到订单确认页面
      final cartIdQuantity = {
        cartAdd.cartId: cartAdd.quantity,
      };
      await Navigator.of(context).pushNamed(
        OrderConfirmScreen.routeName,
        arguments: OrderConfirmScreenArgs(cartIdQuantity, portIds: _selectedPortIds),
      );
      // 返回后刷新列表
      _onRefresh();
      // 清空选择
      setState(() {
        _selectedPortIds.clear();
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      EasyLoading.showToast("${e.message}");
    }
  }
}
